﻿using System.Collections;
using System.Collections.Generic;
using System;

namespace Utility.TaskSystem
{
	public static class Tasks
	{
		public static Task New (IEnumerator<Task> co_func)
		{
			return new CoroutineTask (co_func);
		}

		public static Task Wait (int frames = 1)
		{
			return new WaitUpdatesTask (frames);
		}

		public static Task WaitUntil (Func<bool> predicate)
		{
			return new WaitUntilTask (predicate);
		}

		public static Task WaitWhile (Func<bool> predicate)
		{
			return new WaitWhileTask (predicate);
		}

		#region task classes
		public class WaitUpdatesTask : Task
		{
			int count = 0;
			int n;

			public WaitUpdatesTask (int n)
			{
				this.n = n;
			}

			protected override void OnUpdate ()
			{
				if (count < n)
				{
					count++;
				}
				else
				{
					Done ();
				}
			}
		}

		public class WaitUntilTask : Task
		{
			Func<bool> predicate;

			public WaitUntilTask (Func<bool> predicate)
			{
				this.predicate = predicate;
			}

			protected override void OnUpdate ()
			{
				if (predicate ())
				{
					Done ();
				}
			}
		}

		public class WaitWhileTask : Task
		{
			Func<bool> predicate;

			public WaitWhileTask (Func<bool> predicate)
			{
				this.predicate = predicate;
			}

			protected override void OnUpdate ()
			{
				if (!predicate ())
				{
					Done ();
				}
			}
		}
		#endregion
	}
}